# 编写SKU表的业务
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from apps.goods.models import SKU, GoodsCategory, SPUSpecification
from apps.meiduo_admin.utils import NumPage
from apps.meiduo_admin.serializers.skus import SKUSerialzier, SPUSpecificationSerializer


class SKUSView(ModelViewSet):
    # 指定序列化器
    serializer_class = SKUSerialzier
    # 指定查询集
    queryset = SKU.objects.all()
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定分页
    pagination_class = NumPage

    # 重写GenericAPIView类中的获取数据方法get_queryset
    def get_queryset(self):
        # 获取关键字keyword   keyword是查询字符串数据  request.query_params 获取查询字符串数据
        keyword = self.request.query_params.get('keyword')
        # 根据关键返回不同的数据内容
        if keyword == '' or keyword == None:
            return self.queryset
        else:
            return SKU.objects.filter(name__contains=keyword)  # contains 是否包含

    # 获取三级分类数据
    @action(methods=['get'], detail=False)
    def categories(self, request):
        # 获取三级分类数据  自关联表中关联外键为parent 下级查询上级相当于副表查询主表  上级查询下级相当于主表查询副表
        # parent = None 上一级为空，当前查询级别就是第一级获取一级分类数据
        # subs = None 下一级为空  当前查询级别就是第三级级，获取第三级分类数据
        goodscategories = GoodsCategory.objects.filter(subs=None)
        # 构造结构进行返回
        data_list = []
        for goodscategory in goodscategories:
            data_list.append({
                'id': goodscategory.id,
                'name': goodscategory.name
            })

        return Response(data_list)

    # 获取规格及规格选项信息
    def specs(self, request, pk):
        # 根据spu的ID查询规格表获取对应的规格数据
        specs = SPUSpecification.objects.filter(spu_id=pk)
        # 构造数据进行返回
        ser = SPUSpecificationSerializer(specs, many=True)
        return Response(ser.data)
